package com.gelian.demo;


import android.content.Context;
import android.text.TextUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Date;

public class ExceptionHandler implements UncaughtExceptionHandler {
    //    public static String TAG = "TAOJIE";

    //    private static final int MAX_LOG_MESSAGE_LENGTH = 200000;
    //
    //    private static final long LOG_OUT_TIME = 1000 * 60 * 60 * 24 * 5;

    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    //    private static final String SD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();


    //    private static final String LOG_DIR= SD_PATH + "/welearn/log/error/";

    //    private static final SimpleDateFormat FILENAME_FORMAT =
    //            new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.CHINESE);

    private static final UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();

    //    private String verName;
    //
    //    private int verCode;
    //
    //    private String phone_model;

    private int phone_sdk;

    public ExceptionHandler(Context context) {
        //        PackageManager pm = context.getPackageManager();
        try {
            //            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            //            verName = pi.versionName;
            //            verCode = pi.versionCode;
            //            phone_model = android.os.Build.MODEL;
            phone_sdk = android.os.Build.VERSION.SDK_INT;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean makeDirs(String filePath) {
        String folderName = getFolderName(filePath);
        if (TextUtils.isEmpty(folderName)) {
            return false;
        }

        File folder = new File(folderName);
        return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
    }

    public static String getFolderName(String filePath) {

        if (TextUtils.isEmpty(filePath)) {
            return filePath;
        }

        int filePosi = filePath.lastIndexOf(File.separator);
        return (filePosi == -1) ? "" : filePath.substring(0, filePosi);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        //        final Writer stackResult = new StringWriter();
        //        final PrintWriter printWriter = new PrintWriter(stackResult);
        //        throwable.printStackTrace(printWriter);
        //

        String errLogPath = AppConstant.getErrLogPath();
        //        g.b(errLogPath);
        makeDirs(errLogPath);

        File file = new File(errLogPath);
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file, true);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        if (outputStream != null) {
            PrintStream err = new PrintStream(outputStream);
            throwable.printStackTrace(err);
            err.flush();
            err.close();

            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        //        try {
        //            File dir = new File(LOG_DIR);
        //            if (!dir.isDirectory() && !dir.exists()) {
        //                dir.mkdirs();
        //            }
        //            Time tmtxt = new android.text.format.Time();
        //            tmtxt.setToNow();
        //            String sTime = tmtxt.format("%Y-%m-%d %H:%M:%S");
        //
        //            final File logFile = new File(
        //                    LOG_DIR + "/"
        //                            + FILENAME_FORMAT.format(new Date(System.currentTimeMillis()))
        //                            + ".txt");
        //            logFile.createNewFile();
        //
        //            BufferedWriter bos = new BufferedWriter(new FileWriter(logFile));
        //            bos.write("\t\r\n==================LOG=================\t\r\n");
        ////            bos.write("APP_VERSION:" + verName + "|" + verCode + "\t\r\n");
        ////            bos.write("PHONE_MODEL:" + phone_model + "\t\r\n");
        //            bos.write("ANDROID_SDK:" + phone_sdk + "\t\r\n");
        //            bos.write(sTime + "\t\r\n");
        //            bos.write(stackResult.toString());
        //            bos.write("\t\r\n--------------------------------------\t\r\n");
        //            bos.flush();
        //            StringBuilder log = getLog();
        //            int keepOffset = Math.max(log.length() - MAX_LOG_MESSAGE_LENGTH, 0);
        //            if (keepOffset > 0) {
        //                log.delete(0, keepOffset);
        //            }
        //            bos.write(getLog().toString());
        //            bos.flush();
        //            bos.close();
        //
        //            ThreadPoolUtil.execute(new Runnable() {
        //
        //                @Override
        //                public void run() {
        //                    String content = WeLearnFileUtil.readFile(logFile.getAbsolutePath(), "utf-8").toString();
        //                    WApplication.mNetworkUtil.post(AppConfig.MAIL_URL, content);
        //                }
        //            });
        //
        //        } catch (Exception ebos) {
        //            ebos.printStackTrace();
        //        }
        defaultHandler.uncaughtException(thread, throwable);
    }

    //    public StringBuilder getLog() {
    //
    //        final StringBuilder log = new StringBuilder();
    //        try {
    //            ArrayList<String> commandLine = new ArrayList<String>();
    //            commandLine.add("logcat");//$NON-NLS-1$
    //            commandLine.add("-d");//$NON-NLS-1$
    //
    //            Process process = Runtime.getRuntime().exec(commandLine.toArray(new String[0]));
    //            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    //
    //            String line;
    //            while ((line = bufferedReader.readLine()) != null) {
    //                log.append(line);
    //                log.append(LINE_SEPARATOR);
    //            }
    //        } catch (IOException e) {
    //            LogUtils.e("TAG getLog failed", e.toString());//$NON-NLS-1$
    //        }
    //        return log;
    //    }
}
